package ccm.component.image;

import ccm.component.override.JLabel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

public class ImageJPanel extends JPanel implements MouseListener, ReceiveImageListener
{
    /**
     * 图像监听器
     */
    protected final ArrayList<ImageJPanelListener> imageJPanelListener;
    /**
     * 用于显示图片的label
     */
    protected JLabel imgJLabel;
    /**
     * 缓存图片
     */
    protected BufferedImage image;


    public ImageJPanel()
    {
        this(null);
    }


    public ImageJPanel(BufferedImage image)
    {
        super();
        setLayout(new FlowLayout());
        add(imgJLabel=new JLabel(),BorderLayout.CENTER);
        imgJLabel.addMouseListener(this);
        setImage(image);
        imageJPanelListener=new ArrayList<>();
    }

    /**
     * 更新图片
     */
    protected void updateImg()
    {
        if(image==null)
        {return;}
        imgJLabel.setIcon(new ImageIcon(image));
        imgJLabel.repaint();
    }

    /**
     * 生成一张测试用的图片
     *
     * @param w 图片宽度
     * @param h 图片高度
     * @return 测试用的图片
     */
    static public BufferedImage getTestImage(int w,int h)
    {
        BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        for(int i=0;i<h;++i)
        {
            for(int j=0;j<w;++j)
            {image.setRGB(j,i,(((i+j)&0XFF)<<16)|(((i+j)&0XFF)<<8)|(((i+j)&0XFF)));}
        }
        return image;
    }

    /**
     * 获取图片
     *
     * @return 图片
     */
    public BufferedImage getImage()
    {
        return image;
    }

    /**
     * 设置图片
     *
     * @param image 图片
     */
    public void setImage(BufferedImage image)
    {
        this.image=image;
        updateImg();
        revalidate();
    }

    /**
     * 添加图像监听器监听器
     *
     * @param listener 监听器
     * @throws NullPointerException 监听器为null时抛出此异常
     */
    public void addImageListener(ImageJPanelListener listener) throws NullPointerException
    {
        if(listener==null){throw new NullPointerException();}
        if(!imageJPanelListener.contains(listener)){imageJPanelListener.add(listener);}
    }

    /**
     * 鼠标点击时向上触发点击事件
     */
    public void mouseClicked(MouseEvent e)
    {
        if(e.getSource().equals(imgJLabel))
        {
            imageJPanelListener.forEach(l->l.imageClicked(new ImageEvent(this,1,"clicked",e.getX(),e.getY())));
        }
    }

    public void mousePressed(MouseEvent e)
    {

    }

    public void mouseReleased(MouseEvent e)
    {

    }

    public void mouseEntered(MouseEvent e)
    {

    }

    public void mouseExited(MouseEvent e)
    {

    }

    /**
     * 接收到图像事件
     *
     * @param event
     */
    public void receiveImage(ReceiveImageEvent event)
    {
        setImage(event.getImage());
    }
}
